package org.cx.util;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.cx.constant.UploadCodeType;
import org.cx.entity.PageData;

/**
 * csv导出工具类
 */
public class CommonsCsvUtil {

	public static void exportByList(String[] headers, List<List<String>> dataList) throws FileNotFoundException {
		FileOutputStream fileos = new FileOutputStream("E:/abc.csv");
		exportByList(headers, dataList, fileos);
	}

	public static void exportByList(String[] headers, List<List<String>> dataList, OutputStream os) {
		OutputStreamWriter osw = null;
		CSVFormat csvFormat = null;
		CSVPrinter csvPrinter = null;
		try {
			osw = new OutputStreamWriter(os, "GBK");//如果是UTF-8时，WPS打开是正常显示，而微软的excel打开是乱码,
			csvFormat = CSVFormat.DEFAULT.withHeader(headers);
			csvPrinter = new CSVPrinter(osw, csvFormat);
			for (int i = 0; i < dataList.size(); i++) {
				List<String> values = dataList.get(i);
				csvPrinter.printRecord(values);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(os, csvPrinter);
		}
	}

	public static void exportByLinked(String[] headers, List<LinkedHashMap<String, Object>> dataList)
			throws FileNotFoundException {
		FileOutputStream fileos = new FileOutputStream("E:/abc.csv");
		exportByLinked(headers, dataList, fileos);
	}

	public static void exportByLinked(String[] headers, List<LinkedHashMap<String, Object>> dataList, OutputStream os) {
		OutputStreamWriter osw = null;
		CSVFormat csvFormat = null;
		CSVPrinter csvPrinter = null;
		try {

			osw = new OutputStreamWriter(os, "GBK");
			csvFormat = CSVFormat.DEFAULT.withHeader(headers);
			csvPrinter = new CSVPrinter(osw, csvFormat);

			for (int i = 0; i < dataList.size(); i++) {
				List<String> values = new ArrayList<String>();
				LinkedHashMap<String, Object> rowHashMap = dataList.get(i);
				Set<String> keys = rowHashMap.keySet();
				for (String key : keys) {
					values.add(String.valueOf(rowHashMap.get(key)));
				}
				csvPrinter.printRecord(values);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(os, csvPrinter);
		}
	}
	
	public static void exportByPDList(String[] headers,String[] dataFilds, List<PageData> dataList,String fileName, HttpServletResponse response) throws IOException {
		response.reset();
		response.setContentType("text/csv; charset=UTF-8");
        response.setHeader("content-disposition", "attachment;filename=" + fileName + ".csv");
        OutputStream outputStream = response.getOutputStream();

		exportByPDList(headers,dataFilds, dataList, outputStream);
	}
	
	public static void exportByPDList(String[] headers,String[] dataFilds, List<PageData> dataList, OutputStream os) {
		OutputStreamWriter osw = null;
		CSVFormat csvFormat = null;
		CSVPrinter csvPrinter = null;

		try {
			osw = new OutputStreamWriter(os, "GBK");//如果是UTF-8时，WPS打开是正常显示，而微软的excel打开是乱码,
			csvFormat = CSVFormat.DEFAULT.withHeader(headers);
			csvPrinter = new CSVPrinter(osw, csvFormat);
			for (int i = 0; i < dataList.size(); i++) {
				PageData pd = dataList.get(i);
				
				List<Object> values = new ArrayList<Object>();
				for(String fildName : dataFilds){
					values.add(pd.get(fildName));
				}
				csvPrinter.printRecord(values);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(os, csvPrinter);
		}
	}
	
	//01.获取输出流
	public static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws IOException {
		response.reset();
		response.setContentType("text/csv; charset=UTF-8");
        response.setHeader("content-disposition", "attachment;filename=" + fileName + ".csv");
        return response.getOutputStream();
	}
	//02.获取CSV对象
	public static CSVPrinter getCSVPrinter(String[] headers,OutputStream os) throws IOException {
		OutputStreamWriter osw = null;
		CSVFormat csvFormat = null;
		osw = new OutputStreamWriter(os, "GBK");//如果是UTF-8时，WPS打开是正常显示，而微软的excel打开是乱码,
		csvFormat = CSVFormat.DEFAULT.withHeader(headers);
		return new CSVPrinter(osw, csvFormat);
	}
	//03.写入数据
	public static CSVPrinter exportData(String[] dataFilds, List<PageData> dataList,CSVPrinter csvPrinter) throws IOException {
		dataList.stream().forEach((pd -> {
						List<Object> values = new ArrayList<Object>();
						for(String fildName : dataFilds){
							values.add(pd.get(fildName));
						}
						try {
							csvPrinter.printRecord(values);
						} catch (Exception e) {
							e.printStackTrace();
						}
            		}));
		return csvPrinter;
	}

	//04.输出流，关闭流
	public static void close(OutputStream os, CSVPrinter csvPrinter) {
		if (csvPrinter != null) {
			try {
				csvPrinter.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				csvPrinter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (os != null) {
			try {
				os.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) throws Exception {

		List<String> headerList = new ArrayList<>(Arrays.asList("时间", "问题", "意图", "意图Data"));
		List<List<String>> dataList = new ArrayList<>();

		for (int i = 0; i < 1000000; i++) {
			List<String> rowList = new ArrayList<String>();
			rowList.add("张  三_"+i);
			rowList.add("2 ,./  0 _"+i);
			rowList.add("Gold_getPrice _"+i);
			rowList.add("mmons-csv,  由两大核心对象组成 ,CSVParser.（解析）,CSVPrinter（写csv）,");
			dataList.add(rowList);
		}

		String[] headers = new String[headerList.size()];
		headerList.toArray(headers);
		exportByList(headers, dataList);
		
		System.out.println("=======结束==========");
	}
}
